<template>
  <div class="material-inspection-page">
    <div class="breadcrumb">
      <Breadcrumb :data="breadcrumbData"></Breadcrumb>
    </div>
    <main>
      <div class="search-container">
        <div class="search-item">
          <div class="content">
            <el-input
              v-model="condition"
              placeholder="请输入材料名称或状态"
              @blur="handleSearch"
              @keydown.native.enter="handleSearch">
            </el-input>
          </div>
          <div class="label">时间：</div>
          <div class="content">
            <el-date-picker
              v-model="searchDate"
              format="yyyy-MM-d"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请选择时间">
            </el-date-picker>
          </div>
          <div class="content">
            <el-select v-model="status">
              <el-option label="进场" value="1">进场</el-option>
              <el-option label="领用" value="2">领用</el-option>
            </el-select>
          </div>
          <el-button class="search-btn" type="primary" @click="handleSearch">
            <i class="el-icon-search"></i>
          </el-button>
          <el-button type="primary" @click="handleRefresh">
            <i class="el-icon-refresh"></i>
          </el-button>
        </div>
        <div class="search-item">
          <el-button v-if="hasTabAdd" type="primary" @click="handleAdd">新增</el-button>
          <el-button v-if="hasTabSet" type="primary" @click="handleAcquire">领用</el-button>
        </div>
      </div>
      <el-table
        v-show="status === '1'"
        class="table-container"
        :data="tableData"
        v-loading="tableLoading"
        element-loading-custom-class="custom-load"
        row-key="id">
        <el-table-column label="序号" type="index" width="70" align="center"></el-table-column>
        <el-table-column label="材料名称" prop="materialTypeName" align="center"></el-table-column>
        <el-table-column label="规格/型号" prop="model" align="center"></el-table-column>
        <el-table-column label="总数" prop="materialNum" align="center"></el-table-column>
        <el-table-column label="剩余数量" prop="surplusNum" align="center"></el-table-column>
        <el-table-column label="单位" prop="unit" align="center"></el-table-column>
        <el-table-column label="材料厂家" prop="materialFactory" align="center"></el-table-column>
        <el-table-column label="收货人" prop="receiveUserName" align="center"></el-table-column>
        <el-table-column label="是否合格" prop="acceptFlag" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.acceptFlag === '1'">合格</span>
            <span v-else-if="scope.row.acceptFlag === '0'">不合格</span>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column label="进场日期" prop="approachDate" align="center"></el-table-column>
        <el-table-column label="检测报告" prop="inspectUrl" align="center" width="150">
          <template slot-scope="scope">
            <div class="file-text" v-if="scope.row.inspectUrl">
              <el-image
                v-if="/\.jpg|\.jpeg|\.png$/.test(scope.row.inspectUrl)"
                class="img"
                :src="scope.row.inspectList[0]"
                :preview-src-list="scope.row.inspectList">
              </el-image>
              <span
                v-else
                class="file-name"
                :title="files(scope.row.inspectUrl).name"
                @click="handleDownLoad(scope.row.inspectUrl)">
                  {{ files(scope.row.inspectUrl).name }}
                </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="附件" prop="annexUrl">
          <template slot-scope="scope">
            <el-image
              v-if="/\.jpg|\.jpeg|\.png$/.test(scope.row.annexUrl)"
              class="img"
              :src="scope.row.annexList[0]"
              :preview-src-list="scope.row.annexList">
            </el-image>
            <span
              v-else
              class="file-name"
              @click="handleDownLoad(scope.row.annexUrl)">
              {{ setFileName(scope.row.annexUrl) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <span v-if="hasTableDetail" class="btn" @click="handleView(scope.row)">查看</span>
            <span
              v-if="hasTableEdit && scope.row.hasEdit"
              class="btn"
              @click="handleEdit(scope.row)">编辑</span>
            <span
              v-if="hasTableDel && scope.row.hasDelete"
              class="btn"
              @click="handleDelete(scope.row)">删除</span>
          </template>
        </el-table-column>
        <div class="empty-content" slot="empty">
          <i class="iconfont iconwushuju"></i>
          <p>暂无数据</p>
        </div>
      </el-table>
      <el-table
        v-show="status === '2'"
        class="table-container"
        :data="tableData"
        v-loading="tableLoading"
        element-loading-custom-class="custom-load"
        row-key="id">
        <el-table-column label="领用人" prop="claimUserName" align="center"></el-table-column>
        <el-table-column label="领用单位" prop="claimCompany" align="center"></el-table-column>
        <el-table-column label="抄送人" prop="copyUserName" align="center"></el-table-column>
        <el-table-column label="附件" key="annexUrl">
          <template slot-scope="scope">
            <el-image
              v-if="/\.jpg|\.jpeg|\.png$/.test(scope.row.annexUrl)"
              class="img"
              :src="$checkUrl(scope.row.annexUrl)"
              :preview-src-list="[$checkUrl(scope.row.annexUrl)]">
            </el-image>
            <span
              v-else
              class="file-name"
              @click="handleDownLoad(scope.row.annexUrl)">
              {{ setFileName(scope.row.annexUrl) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="进场日期" prop="claimDate" align="center"></el-table-column>
        <el-table-column label="操作" key="annexUrl-handler">
          <template slot-scope="scope">
            <span v-if="hasTableDetail" class="btn" @click="handleViewOut(scope.row)">查看</span>
            <span
              v-if="hasTableDel && scope.row.hasDelete"
              class="btn"
              @click="handleDeleteStockOut(scope.row)">删除</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="total > 10"
        :page-size="pageSize"
        :current-page="pageNo"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </main>
    <add-input-material
      :visible="visible"
      :type="type"
      :loading="btnLaoding"
      :options="currentData"
      @cancel="visible = false"
      @submit="handleSave">
    </add-input-material>
    <material-collection
      :visible="collectionVisible"
      :type="collectionType"
      :options="collectionData"
      :loading="collectionLaoding"
      @cancel="collectionVisible = false"
      @submit="handleCollection">
    </material-collection>
    <view-material
      :visible="viewVisible"
      :type="status"
      :options="materialData"
      @cancel="viewVisible = false">
    </view-material>
  </div>
</template>

<script>
import Breadcrumb from '@/components/public/Breadcrumb';
import AddInputMaterial from '@/components/project/material/AddInputMaterial';
import MaterialCollection from '@/components/project/material/MaterialCollection';
import viewMaterial from '@/components/project/material/viewMaterial';

export default {
  data() {
    return {
      breadcrumbData: [
        { name: '材料管理' },
        { name: '进场原材料管理' }
      ],
      status: '1',
      searchDate: '',
      // 列表数据
      tableData: [],
      tableLoading: false,
      total: 0,
      pageSize: 10,
      pageNo: 1,
      hasSearch: false,
      visible: false,
      type: 'add',
      currentData: {},
      condition: '',
      btnLaoding: false,
      collectionType: 'add',
      collectionData: {},
      collectionVisible: false,
      collectionLaoding: false,
      viewVisible: false,
      materialData: {},
    };
  },
  computed: {
    projectId() {
      return this.$store.state.currentProjectId;
    },
    userInfo() {
      return this.$store.state.userInfo;
    }
  },
  watch: {
    visible(val) {
      if (!val) {
        this.currentData = {};
      }
    },
    viewVisible(val) {
      if (!val) this.materialData = {};
    },
    status(val) {
      this.clear();
      this.getData();
    }
  },
  created() {
    this.getData();
  },
  components: {
    Breadcrumb,
    viewMaterial,
    AddInputMaterial,
    MaterialCollection
  },
  methods: {
    getData() {
      const params = {
        pageNum: this.pageNo,
        pageSize: this.pageSize,
        projectId: this.projectId,
      };
      if (this.hasSearch) {
        params.condition = this.condition;
        params.searchDate = this.searchDate;
      }
      if (this.status === '1') {
        this.getTableData(params);
        return;
      }
      this.getStockOutList(params);
    },
    // 离场列表
    async getStockOutList(params) {
      this.tableLoading = true;
      const { success, data: {
        data
      }} = await this.$Model.getStockOutList(params);
      this.tableLoading = false;
      if (success && data) {
        const list = data.list || [];
        const { uuid } = this.userInfo;
        this.tableData = list.map(item => {
          const { createUser, status } = item;
          return {
            ...item,
            hasEdit: uuid === createUser && status === '1',
            hasDelete: true || uuid === createUser,
          };
        });
        this.total = data.total || 0;
      }
    },
    /**
     * 获取列表数据
     */
    async getTableData(params) {
      this.tableLoading = true;
      const { success, data: {
        data
      }} = await this.$Model.materialStockInList(params);
      this.tableLoading = false;
      if (success && data) {
        const list = data.list || [];
        const { uuid } = this.userInfo;
        this.tableData = list.map(item => {
          const { createUser, status, inspectUrl, annexUrl } = item;
          const inspectList = inspectUrl
            ? inspectUrl.split(',').map(url => this.$checkUrl(url))
            : [];
          const annexList = annexUrl
            ? annexUrl.split(',').map(url => this.$checkUrl(url))
            : [];
          return {
            ...item,
            inspectList,
            annexList,
            hasEdit: uuid === createUser && status === '1',
            hasDelete: uuid === createUser,
          };
        });
        this.total = data.total || 0;
      }
    },
    /**
     * pageSize 改变时会触发
     * @param pageSize 每页条数
     */
    handleSizeChange(pageSize) {
      this.pageNo = 1;
      this.pageSize = pageSize;
      this.getData();
    },
    /**
     * currentPage 改变时会触发
     * @param pageNo 当前页
     */
    handleCurrentChange(pageNo) {
      this.pageNo = pageNo;
      this.getData();
    },
    // 附件
    files(fileUrl) {
      const fileNames = fileUrl ? fileUrl.match(/([^\/])+\.\w+$/) : '';
      const fileName = Array.isArray(fileNames) ? fileNames[0] : '';
      return {
        name: fileName,
        url: this.$checkUrl(fileUrl),
        hasImg: /\.jpg|\.jpeg|\.png$/.test(fileUrl)
      };
    },
    /**
     * 选取文件
     */
    handleFileChange(file, row, index) {
      this.fileUpload(file.raw, row, index);
      return false;
    },
    /**
     * 删除文件
     */
    async handleRemove(fileUrl, index) {
      const { success } = await this.$Model.fileDelete({ filePath: fileUrl });
      const item = this.tableData[index];
      if (success) {
        item.files = [];
        item.fileUrl = '';
      }
    },
    // 设置附件信息
    setFileName(url) {
      const fileNames = url ? url.match(/([^\/])+\.\w+$/) : '';
      return Array.isArray(fileNames) ? fileNames[0] : '';
    },
    handleDownLoad(url) {
      window.open(this.$checkUrl(url));
    },
    // 清除参数
    clear() {
      this.pageNo = 1;
      this.pageSize = 10;
      this.total = 0;
      this.tableLoading = false;
      this.tableData = [];
    },
    // 搜索
    handleSearch() {
      this.clear();
      this.hasSearch = !!this.condition;
      this.getData();
    },
    handleRefresh() {
      this.condition = '';
      this.searchDate = '';
      this.status = '1';
      this.clear();
      this.getData();
    },
    // 新增
    handleAdd() {
      this.currentData = {};
      this.type = 'add';
      this.visible = true;
    },
    // 编辑
    handleEdit(row) {
      this.currentData = { ...row };
      this.type = 'edit';
      this.visible = true;
    },
    // 查看
    handleView(row) {
      this.materialData = { ...row };
      this.viewVisible = true;
    },
    // 领用
    handleAcquire() {
      this.collectionVisible = true;
    },
    // 删除
    handleDelete(row) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        type: 'warning'
      }).then(async () => {
        const { success } = await this.$Model.delStockInMaterial({
          ids: row.id
        });
        if (success) {
          this.$message.success('删除成功');
          this.clear();
          this.getData();
        }
      });
    },
    // 离场查看
    handleViewOut(row) {
      this.materialData = { ...row };
      this.viewVisible = true;
    },
    // 材料离场删除
    handleDeleteStockOut(row) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        type: 'warning'
      }).then(async () => {
        const { success } = await this.$Model.delStockOut({
          ids: row.id
        });
        if (success) {
          this.$message.success('删除成功');
          this.clear();
          this.getData();
        }
      });
    },
    // 保存
    async handleSave(data) {
      const params = {
        ...data,
        projectId: this.projectId,
        createUser: this.userInfo.uuid,
      };
      if (this.type === 'add') delete params.id;
      this.btnLaoding = true;
      const { success } = this.type === 'add'
        ? await this.$Model.addStockInMaterial(params)
        : await this.$Model.updateStockInMaterial(params);
      this.btnLaoding = false;
      if (success) {
        this.getData();
        this.visible = false;
        this.$message.success(`${this.type === 'add' ? '新增' : '修改'}成功`);
      }
    },
    // 确认领用
    async handleCollection(data) {
      const { materialOutRecords } = data;
      if (!materialOutRecords.length) {
        return this.$message.warning('请添加材料');
      }
      const params = {
        ...data,
        createUser: this.userInfo.uuid,
        projectId: this.projectId,
        materialOutRecords: materialOutRecords.map(v => {
          const { claimNum, id: materialInId } = v;
          return {
            materialInId,
            claimNum
          };
        }),
      };
      if (this.collectionType === 'add') delete params.id;
      this.collectionLaoding = true;
      const { success } = await this.$Model.addStockOut(params);
      this.collectionLaoding = false;
      if (success) {
        this.getData();
        this.$message.success('领用成功');
        this.collectionVisible = false;
      }
    }
  }
};
</script>

<style scoped lang="scss">
  @import '../../../assets/styles/table';

  .material-inspection-page {
    width: 100%;
    height: 100%;
    background-color: $mainBg;
    overflow: hidden;
    main {
      width: 100%;
      height: calc(100% - 50px);
      padding: 20px;
      .search-container {
        width: 100%;
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
        .search-item {
          display: flex;
          align-items: center;
          .el-input {
            width: 300px;
            margin-right: 20px;
          }
        }
        .search-btn {
          margin-left: 20px;
        }
      }
      .table-container {
        height: calc(100% - 120px);
        /deep/ .el-table__body-wrapper {
          height: calc(100% - 50px);
          padding-bottom: 46px;
          overflow-y: auto;
          .btn {
            padding: 0 5px;
            cursor: pointer;
            color: $mainColor;
          }
          .img {
            width: 60px;
            height: 60px;
          }
          .file-name {
            height: 60px;
            display: flex;
            justify-content: flex-start;
            align-items: center;
          }
        }
        /deep/ .el-table__header {
          th.is-leaf .el-button span {
            color: #fff;
          }
        }
      }

    }
  }
</style>
